package com.smh.yunpicturebackend.utils;

import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTVerificationException;
import com.auth0.jwt.interfaces.Claim;
import com.smh.yunpicturebackend.pojo.constant.AuthConstant;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * @author shiminghui
 * @date 2025/6/14 21:18
 * @description: jwt 工具类
 */
public class JWTUtils {

    /**
     * jwt 签名算法
     */
    private static final Algorithm ALGORITHM = Algorithm.HMAC256(AuthConstant.JWT_SECRET_KEY);
    /**
     * jwt 过期时间
     */
    private static final long EXPIRE_TIME = 1000 * 60 * 60 * 24;

    /**
     * 生成token
     * @param claims 负载数据
     * @param expireTime 过期时间
     * @return  token
     */
    public static String generateToken(Map<String, Object> claims, Long expireTime){
        return JWT.create()
                .withPayload(claims)
                .withExpiresAt(new Date(System.currentTimeMillis() + expireTime))
                .sign(ALGORITHM);
    }

    /**
     * 生成token
     * @param claims 负载数据
     * @return  token
     */
    public static String generateToken(Map<String, Object> claims){
        return generateToken(claims, EXPIRE_TIME);
    }

    /**
     * 验证token
     * @param token token
     * @return  true/false
     */
    public static boolean verify(String token){
        try {
            return JWT.require(ALGORITHM).build().verify(token) != null;
        } catch (JWTVerificationException e) {
            return false;
        }
    }

    /**
     * 解析token
     * @param token token
     * @return   claims
     */
    public static Map<String, Claim> decode(String token){
        return JWT.require(ALGORITHM).build().verify(token).getClaims();
    }

    public static void main(String[] args) {
        /**
         * 负载部分是通过base64编码的,可以直接解析出来,所以不要放密码等信息
         */

        HashMap<String, Object> map = new HashMap<>();
        map.put("id", 1);
        map.put("username", "shiminghui");
        map.put("password", "123456");

        String s = generateToken(map);
        System.out.println(s);
        s= s+"1";
        System.out.println(s);
        System.out.println(decode(s));
    }

}